from django.shortcuts import render,redirect
from django.shortcuts import reverse
from django.http import HttpResponse
from django.core.mail import send_mail
from django.contrib.auth import authenticate,login, logout
from  user.models import User, Address
from goods.models import GoodsSKU
from order.models import OrderInfo,OrderGoods
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from celery_tasks.tasks import send_register_active_email
from django_redis import get_redis_connection
from django.core.paginator import Paginator


import re

# Create your views here.


def register(request):
    if request.method == 'GET':
        return render(request,'df_user/register.html')
    else:
        user_name = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        email = request.POST.get('email')

        if not all([user_name, pwd, email]):
            return render(request, 'df_user/register.html', {'errmsg': 'Wrong Info'})

        confirm_pwd = request.POST.get('confirm_pwd')

        allow = request.POST.get('allow')
        if allow != 'on':
            return render(request, 'df_user/register.html', {'errmsg': 'Wrong Info'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'df_user/register')
        # 使用Django自带user认证体系创建用户
        try:
            user = User.objects.create_user(username=user_name, password=pwd, email=email)
            user.is_active = 0
            user.save()

            # 加密身份信息，激活token
            serializer = Serializer(settings.SECRET_KEY, 3600)
            data = {'confirm':user.id}
            token = serializer.dumps(data)
            token = token.decode()

            # 发送激活邮件
            send_register_active_email.delay(email, user_name, token)

        except Exception as e:
            # return redirect(reverse('user:register'), {'errmsg': '用户名已存在'})
            print('=================')
            print(e)
        return redirect(reverse('goods:index'))


def userLogin(request):
    if request.method=='GET':
        if 'username' in request.COOKIES:
            username = request.COOKIES['username']
            check = 'checked'
            password = request.COOKIES['password']
        else:
            username = ''
            check = ''
            password = ''
        return render(request,'df_user/login.html',{'username':username,
                                                    'password':password,
                                                    'check':check})
    else:
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        print(username)
        if not all([username,pwd]):
            return render(request, 'df_user/login.html',{'errmsg':'数据不完整'})

        # 判断登陆后要跳转的页面
        next_url = request.GET.get('next', reverse('goods:index'))
        print(next_url)
        response = redirect(next_url)

        # 是否记住用户名
        rember = request.POST.get('jizhu')
        if rember == 'on':
            response.set_cookie("username",username,max_age=7*24*3600)
            response.set_cookie("password",pwd,max_age=7*24*3600)
        else:
            response.delete_cookie('username')
        user = authenticate(username=username, password=pwd)
        if user is not None:
            if user.is_active:
                # 记录登陆状态
                login(request, user)
                return response
            else:
                return render(request, 'df_user/login.html',{'errmsg':'用户未激活'})
        else:
            return render(request, 'df_user/login.html', {'errmsg': '用户名或密码错误'})
'''
        try:
            user = User.objects.get(username=username)
            password = user.password
            print(password)

            if pwd != password:
                return render(request, 'df_user/login.html',{'errmsg':'密码不正确'})
            else:
                return redirect(reverse('goods:index'),{'user':user})
        except Exception as e:
            print(e)
            return render(request, 'df_user/login.html',{'errmsg':'用户不存在'})
'''

'''
def register_handle(request):
    user_name = request.POST.get('user_name')
    pwd = request.POST.get('pwd')
    email = request.POST.get('email')

    if not all([user_name, pwd, email]):
        return render(request,'df_user/register.html', {'errmsg':'Wrong Info'})

    confirm_pwd = request.POST.get('confirm_pwd')

    allow = request.POST.get('allow')
    if allow != 'on':
        return render(request,'df_user/register.html', {'errmsg':'Wrong Info'})

    if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
        return render(request, 'df_user/register')
    # 使用Django自带user认证体系创建用户
    try:
        user = User.objects.create_user(user_name, pwd,email)
        user.is_active = 0
        user.save()
    except:
        return redirect(reverse('user:register'), {'errmsg':'用户名已存在'})
    return redirect(reverse('goods:index'))
'''


def UserLogout(request):
    logout(request)
    return redirect(reverse('goods:index'))


def register_exist(request):
    username = request.GET.get('uname')
    try:
        User.objects.get(username=username)
        user = 1
    except:
        user = 0
    return JsonResponse({"data":user})



def UserActive(request, token):
    serializer = Serializer(settings.SECRET_KEY, 3600)
    try:
        info = serializer.loads(token)
        user_id = info['confirm']

        user = User.objects.get(id=user_id)
        user.is_active = 1
        user.save()

        return redirect(reverse('user:login'))
    except SignatureExpired as e:
        return HttpResponse('激活时间已过期')


@login_required
def user_center_info(request):
    user = request.user
    address = Address.objects.get_default_address(user)

    # 查询用户历史纪录
    conn = get_redis_connection('default')
    history_key = 'history_%s'%user.id
    goods_sku = conn.lrange(history_key, 0, 4)

    goods_list = []
    for sku_id in goods_sku:
        good = GoodsSKU.objects.get(id=sku_id)
        goods_list.append(good)
    return render(request, 'df_user/user_center_info.html',{'address':address,
                                                            'goods_history':goods_list})


@login_required
def user_center_order(request, num):
    user = request.user
    orders = OrderInfo.objects.filter(user = user).order_by('-create_time')

    # for i in range(len(orders)):
    #     order_goods = OrderGoods.objects.filter(order=orders[i])
    #     goods_list.append(order_goods)
    for order in orders:
        order_goods = OrderGoods.objects.filter(order = order.order_id)
        for sku in order_goods:
            count = sku.count
            price = sku.price
            # 计算小计
            amount = count * price
            sku.amount = amount

        # 动态给`order`增加`订单商品`属性
        order.order_skus = order_goods
        order.order_status_name = OrderInfo.ORDER_STATUS[order.order_status]



    paginator = Paginator(orders, 1)
    # 判断页码
    try:
        page = int(num)
    except:
        page = 1

    if page > paginator.num_pages:
        page = 1

    skus_page = paginator.page(page)


    for order in orders:
        print(order.order_skus)
    print('=======')
    context = {"page":skus_page, 'orders':orders}
    return render(request, 'df_user/user_center_order.html',context)


@login_required
def user_center_site(request):
    if request.method == 'GET':

        # 获取默认地址
        user = request.user
        '''
        try:
            default_address = Address.objects.get(user=user, is_default=True)
        except:
            default_address = False
        '''
        default_address = Address.objects.get_default_address(user)
        if default_address:
            return render(request, 'df_user/user_center_site.html', {'default_address':default_address})
        else:
            return render(request, 'df_user/user_center_site.html',{'default_address':default_address})

    else:
        receiver = request.POST.get('ushou')
        phone = request.POST.get('uphone')
        zipcode = request.POST.get('uyoubian')
        address = request.POST.get('uaddress')

        if not all([receiver, phone, zipcode, address]):
            return render(request, 'df_user/user_center_site.html', {'errmsg':'信息不完整'})

        if not re.match(r'',phone):
            return render(request, 'df_user/user_center_site.html', {'errmsg':'手机号不正确'})
        user = request.user

        default_address = Address.objects.get_default_address(user)
        if default_address:
            is_default = False
        else:
            is_default = True

        Address.objects.create(user=user,
                               receiver = receiver,
                               addr = address,
                               zip_code = zipcode,
                               phone = phone,
                               is_default = is_default)

        return redirect(reverse('user:site'))